package com.wholeintech.utils;

import android.app.AlarmManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.util.Log;

import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Locale;

public class CrashExceptionUtils implements Thread.UncaughtExceptionHandler {
    private static CrashExceptionUtils INSTANCE = new CrashExceptionUtils();
    private static final String TAG = "CrashHandler";
    private static String serialID;
    private DateFormat formatter;
    private static Context mContext;
    private PendingIntent restartIntent;
    private Thread.UncaughtExceptionHandler mDefaultHandler;

    // HUD日志上报接口:
    // http://www.cocopico.com/ecar/api/saveLog.co
    // 参数:
    // logFile 日志文件
    // filename 文件名

    // 日志文件保存在web服务器 /usr/share/tomcat/coco.hud.logs 目录下

    private CrashExceptionUtils() {
        formatter = new SimpleDateFormat("yyyy-MM-dd-HH-mm-ss", Locale.CHINA);
    }

    public static CrashExceptionUtils getInstance() {
        return INSTANCE;
    }

    public <T> void init(Context context, Class<T> startClazz, String serID) {
        mContext = context;
        mDefaultHandler = Thread.getDefaultUncaughtExceptionHandler();
        Thread.setDefaultUncaughtExceptionHandler(this);
        serialID = serID;
        Intent intent = new Intent(context, startClazz);
        intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        restartIntent = PendingIntent.getService(mContext, 0, intent, PendingIntent.FLAG_CANCEL_CURRENT);
    }

    private boolean handleException(Throwable throwable) {
        if (throwable == null)
            return false;

//		saveCrashInfo(throwable);

        return true;
    }

	/*private File saveCrashInfo(Throwable throwable) {
		StringBuffer stringbuffer = new StringBuffer();
		StringWriter stringwriter = new StringWriter();
		PrintWriter printwriter = new PrintWriter(stringwriter);
		throwable.printStackTrace(printwriter);
		Throwable throwable1 = throwable.getCause();
		if (throwable1 != null) {
			throwable1.printStackTrace(printwriter);
		}
		printwriter.close();
		stringbuffer
				.append(Build.MODEL + "_" + Build.DISPLAY + MiscUtils.getVersionName(mContext) + "_" + serialID + "\n");
		stringbuffer.append(stringwriter.toString());
		File file = null;
		try {
			// long l = System.currentTimeMillis();
			String s = formatter.format(new Date());
			// String filename = (new
			// StringBuilder("crash-")).append(s).append("-").append(l).append(".log").toString();
			String filename = (new StringBuilder("crash-")).append(serialID + "-").append(s).append(".log").toString();
			if (Environment.getExternalStorageState().equals("mounted")) {
				file = new File(FileHelper.crashFilePath);
				if (!file.exists()) {
					file.mkdirs();
				} else {
					// 如果此文件夹下文件大于１００Ｍ将全部删除掉
					if (FileHelper.isMorethanHundredMega(FileHelper.getDirSize(file.toString()))) {
						FileHelper.deleteDir(file);
						file.mkdirs();
					}
				}
				MyLog.d(TAG, "saveCrashInfo:" + filename);
				FileOutputStream fileoutputstream = new FileOutputStream(new File(file, filename));
				fileoutputstream.write(stringbuffer.toString().getBytes());
				fileoutputstream.close();
			}
		} catch (Exception e) {
			MyLog.e(TAG, "CrashHandler" + "an error occured while writing file..." + e);
		}
		return file;
	}*/

	/*public static void sendCrashLogToServer() {
		SimpleDateFormat simpledateformat = new SimpleDateFormat("yyyy-MM-dd-HH-mm-ss");

		final File srcFileDir = new File(FileHelper.crashFilePath);
		final File destFileDir = new File(FileHelper.crashZipFilePath);

		final String s1 = simpledateformat.format(new Date());

		MyLog.d(TAG, "sendErrorLogToServer...");

		if (!srcFileDir.exists())
			return;

		File afile[] = srcFileDir.listFiles();
		try {
			if (afile.length == 0)
				return;

			if (!destFileDir.exists())
				destFileDir.mkdir();

			new Thread(new Runnable() {

				@Override
				public void run() {
					String srcFile = (new StringBuilder(String.valueOf(srcFileDir.getAbsolutePath()))).toString();

					String destFile = (new StringBuilder(String.valueOf(destFileDir.getAbsolutePath())))
							.append("/crash-").append(serialID + "-").append(s1).append(".zip").toString();
					try {
						ZipUtils.doCompress(srcFile, destFile);
						FileHelper.deleteDir(new File(FileHelper.crashFilePath));
						UploadLogUtil mUploadLogUtil = UploadLogUtil.getInstance(mContext);
						mUploadLogUtil.uploadFile(FileHelper.crashZipFilePath);
					} catch (Exception e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
				}
			}).start();
		} catch (Exception exception) {
			exception.printStackTrace();
		}
	}*/

    public void uncaughtException(Thread thread, Throwable throwable) {
        if (!handleException(throwable) && mDefaultHandler != null) {
            mDefaultHandler.uncaughtException(thread, throwable);
            return;
        }
        Log.d(TAG, "uncaughtException ; Restart Activity");
        AlarmManager mgr = (AlarmManager) mContext.getSystemService(Context.ALARM_SERVICE);
        mgr.set(AlarmManager.RTC, System.currentTimeMillis() + 1500, restartIntent); // 1.5秒钟后重启应用
        android.os.Process.killProcess(android.os.Process.myPid());
    }

    /**
     * by levin
     */
    public void forceRestart(Context context) {
        AlarmManager mgr = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
        Log.e(TAG, "restart all service:");
        mgr.set(AlarmManager.RTC, System.currentTimeMillis() + 1500, restartIntent); // 1.5秒钟后重启应用
        android.os.Process.killProcess(android.os.Process.myPid());
    }
}